﻿/*
 * Cratos Desktop
 * Cratos Proxy Paging Collection class
 * 
 * Copyright (c) 2011-2012 Draco
 * 
 * This file is part of Cratos.
 * 
 * Cratos is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * Cratos is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Cratos.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *       .==.        .==.
 *      //'^\\      //^'\\
 *     // ^ ^\(\__/)/^ ^^\\
 *    //^ ^^ ^/6  6\ ^^ ^ \\
 *   //^ ^^ ^/( .. )\^ ^ ^ \\
 *  // ^^ ^/\| V""V|/\^ ^ ^ \\
 * //^^/\/ /  '~~'  \ \/\^ ^ \\
 *  ------------------------------------
 *  HERE BE DRAGONS
 *  
 *  Johan Dercksen - johan@draco.co.za
 */
using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;

using Cratos.Tools.General;
using Cratos.Tools.DataObject;
using Cratos.Desktop.CratosDualWcfService;

namespace Cratos.Desktop
{
	/// <summary>
	/// Cratos Proxy Paging Collection class
	/// </summary>
	public class CratosProxyPagingCollection<T> : CratosProxyBase, IDisposable, ICratosEntityPagingCollectionAccess<T> where T : IDOCratos, new()
	{
		#region Class Constant declarations
		#endregion

		#region Class Event declarations
		/// <summary>
		/// Collection New Page event
		/// </summary>
		public event EntityCollectionNewPageEventHandler NewPage;

		/// <summary>
		/// Collection Error event
		/// </summary>
		public event EntityCollectionErrorEventHandler Error;

		/// <summary>
		/// Error Event
		/// </summary>
		public event EntityCollectionCompletedEventHandler Completed;
		#endregion

		#region Class Variable declarations
		private bool													m_IsDisposed;
		private IDOCratosPagingCollection<T>	doCollection;
		private CDualWcfService								wcfService;
		#endregion

		#region Class Constructors & Destructors
		/// <summary>
		/// Class Constructor
		/// </summary>
		public CratosProxyPagingCollection() : base()
		{
			// Create and Setup the WCF Service
			this.wcfService            = new CDualWcfService();
			this.wcfService.NewPage   += new CratosNewPageEventHandler(this.OnCratosDualWcfServiceCallbackNewPage);
			this.wcfService.Error     += new CratosErrorEventHandler(this.OnCratosDualWcfServiceCallbackError);
			this.wcfService.Completed += new CratosCompletedEventHandler(this.OnCratosDualWcfServiceCallbackCompleted);
		}

		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or
		/// resetting unmanaged resources.
		/// </summary>
		public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }

		/// <summary>
		/// Dispose method doing the disposing
		/// </summary>
		/// <param name="isDisposing"></param>
		protected virtual void Dispose(bool isDisposing)
		{
			// Declare the required variables

			// Check to see if Dispose has already been called.
			if (!this.m_IsDisposed)
			{
				// Dispose the objects if required
				if (isDisposing)
				{
					if (this.wcfService != null) { this.wcfService = null; }
				}
			}

			// Set the disposed indicator
			this.m_IsDisposed = true;

			// Return to calling method
			return;
		}
		#endregion

		#region Class Properties
		#endregion

		#region Class Methods
		/// <summary>
		/// Entity Perform Action
		/// </summary>
		/// <returns>A Boolean indicating success of the method</returns>
		public bool PerformAction(IDOCratosPagingCollection<T> cratosDOCollection)
		{
			// Declare the required variables
			bool							returnValue = false;
			CratosWcfContract	ctCratos    = null;

			try
			{
				// Save the incoming data
				this.doCollection = cratosDOCollection;

				// Clear any relevant data
				this.Errors.Clear();
				this.doCollection.Errors.Clear();

				if (string.IsNullOrEmpty(this.doCollection.DataObject.DBConnectionName))
				{
					this.doCollection.DataObject.DBConnectionName = DOCratosGlobal.DBConnectionName;
				}

				if (this.doCollection.CollectionAction == DOCratosCollectionAction.Retrieve)
				{
					this.doCollection.Clear();
				}

				// Create and Setup the WCF Contract
				ctCratos              = new CratosWcfContract();
				ctCratos.IsCollection = true;
				ctCratos.IsCompressed = true;
				ctCratos.DODataType   = this.doCollection.DataObject.GetType().AssemblyQualifiedName;

				// Serialize the Data Object
				ctCratos.DOStream = cratosDOCollection.CreateSerializeStream();

				// Send the request to the server
				if (this.wcfService.PerformAction(ctCratos))
				{
					// Clear the return data
					this.doCollection.Clear();

					// Update the relevant properties
					this.doCollection.CollectionAction       = DOCratosCollectionAction.None;
					this.doCollection.CollectionActionResult = DOCratosActionResult.NoRecords;

					// Set the successful return value
					returnValue = true;
				}
				else
				{
					this.Errors.Add(new CratosError("EntityAccess", CratosLogSeverity.Exception, "Internal error occurred on Dual WCF Service"));
				}
			}
			catch (Exception runtimeException)
			{
				// Create and setup a new error
				this.Errors.Add(new CratosError("CratosProxyPagingCollection.PerformAction", CratosLogSeverity.Exception,
																				"Runtime error ocurred", runtimeException));
			}
			finally
			{
			}

			// return to calling method
			return (returnValue);
		}
		#endregion

		#region Class Support Methods
		private void OnCratosDualWcfServiceCallbackNewPage(long pageNo, Collection<IDOCratos> doCollection)
		{
			// Declare the required variables

			// Raise the relevant event if required
			if (this.NewPage != null) { this.NewPage(pageNo, doCollection); }

			// Return to calling method
			return;
		}

		private void OnCratosDualWcfServiceCallbackError(Collection<CratosError> errorCollection)
		{
			// Declare the required variables

			// Raise the relevant event if required
			if (this.Error != null) { this.Error(errorCollection); }

			// Return to calling method
			return;
		}

		private void OnCratosDualWcfServiceCallbackCompleted(DOCratosActionResult actionResult, Collection<IDOCratos> doCollection)
		{
			// Declare the required variables

			// Raise the relevant event if required
			if (this.Completed != null) { this.Completed(actionResult, doCollection); }

			// Return to calling method
			return;
		}
		#endregion
	}
}
